﻿using System;
using System.Windows.Forms;
using System.Drawing;
using System.Runtime.InteropServices;
using System.IO;
using System.Collections.Generic;
using System.Threading;

namespace Softony__Viewer
{
    public partial class MainForm : Form
    {

        private static List<string> files = new List<string>();
        public static List<string> Files
        {
            get { return MainForm.files; }
            set { MainForm.files = value; }
        }

        private static int index = 0;
        public static int Index
        {
            get { return MainForm.index; }
            set { MainForm.index = value; }
        }

        private static string lastPath;
        public static string LastPath
        {
            get { return MainForm.lastPath; }
            set { MainForm.lastPath = value; }
        }
       
        private const int WM_NCLBUTTONDOWN = 0xA1;
        private const int HTCAPTION = 0x2;
        [DllImport("user32.dll")]
        public static extern bool ReleaseCapture();
        [DllImport("user32.dll")]
        public static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam);

        public MainForm()
        {
            InitializeComponent();
        }

        public MainForm(string[] args)
        {
            InitializeComponent();
            DisplayImage(args[0]);
            FillArray(args[0]);
        }

        public void DisplayImage(string path)
        {
            try
            {
                LastPath = path;
                Bitmap bm = new Bitmap(path);
                labelError.Visible = false;
                if (pictureBoxDisplay.Image != null)
                    pictureBoxDisplay.Image.Dispose();
                this.pictureBoxDisplay.Image = bm;
                if (this.pictureBoxDisplay.Image != null)
                    if ((this.pictureBoxDisplay.Image.Width <= this.pictureBoxDisplay.Width) && (this.pictureBoxDisplay.Image.Height <= this.pictureBoxDisplay.Height))
                        this.pictureBoxDisplay.SizeMode = PictureBoxSizeMode.CenterImage;
                    else this.pictureBoxDisplay.SizeMode = PictureBoxSizeMode.Zoom;
            }
            catch
            {
                this.pictureBoxDisplay.Image = null;
                labelError.Visible = true;
            }
        }

        public void FillArray(string path)
        {
            Files.Clear();
            string[] formats = openFileDialog.Filter.Split('|')[1].Replace("*", "").Split(';');
            foreach (string fileName in Directory.GetFiles(path.Remove(path.LastIndexOf('\\'))))
            {
                FileInfo fi = new FileInfo(fileName);

                foreach (string format in formats)
                {
                    if ((((fi.Attributes | FileAttributes.Hidden) != fi.Attributes)) && ((fi.Attributes | FileAttributes.System) != fi.Attributes) && (fileName.EndsWith(format)))
                    {
                        Files.Add(fileName);
                    }
                }

                if (fileName == path)
                    Index = Files.Count - 1;
            }
        }

        //protected override void WndProc(ref Message m)
        //{
        //    base.WndProc(ref m);
        //    switch (m.Msg)
        //    {
        //        case 0x0084:
        //            if (m.Result == (IntPtr)1)
        //            {
        //                m.Result = (IntPtr)2;
        //            }
        //            break;
        //    }
        //}

        protected override CreateParams CreateParams
        {
            get
            {
                CreateParams cp = base.CreateParams;
                cp.Style |= 0x40000;
                return cp;
            }
        }

        private void buttonExit_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void buttonMaximize_Click(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Maximized)
                this.WindowState = FormWindowState.Normal;
            else
                this.WindowState = FormWindowState.Maximized;
        }

        private void buttonMinimize_Click(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Minimized;
        }

        private void MainForm_SizeChanged(object sender, EventArgs e)
        {
            pictureBoxPoint.Location = new Point(this.Size.Width / 2 - this.pictureBoxPoint.Size.Width / 2 - 7, this.pictureBoxPoint.Location.Y);
            
            #region LeftPart
            buttonPrevious.Location = new Point(pictureBoxPoint.Location.X - this.buttonPrevious.Size.Width , 0);
            buttonTurnLeft.Location = new Point(this.Size.Width / 2 - 170 - 7, 0);
            buttonTurnRight.Location = new Point(this.buttonTurnLeft.Location.X + 26, 0);
            buttonIncrease.Location = new Point(this.Size.Width / 2 - this.buttonIncrease.Width - 70 - 7, 0);
            trackBarZoom.Location = new Point(buttonIncrease.Location.X - 24, this.trackBarZoom.Location.Y);
            #endregion

            #region RightPart
            buttonNext.Location = new Point(pictureBoxPoint.Location.X + pictureBoxPoint.Size.Width, 0);
            buttonOpen.Location = new Point(this.Size.Width / 2 + 70 - 7, 0);
            buttonDelete.Location = new Point(buttonOpen.Location.X + 40, 0);
            buttonSettings.Location = new Point(buttonDelete.Location.X + 40, 0);
            #endregion
            
            labelError.Location = new Point(this.Size.Width / 2 - this.labelError.Width / 2, this.Size.Height / 2 - this.labelError.Height / 2);
            if(this.pictureBoxDisplay.Image!=null)
                if ((this.pictureBoxDisplay.Image.Width <= this.pictureBoxDisplay.Width) && (this.pictureBoxDisplay.Image.Height <= this.pictureBoxDisplay.Height))
                    this.pictureBoxDisplay.SizeMode = PictureBoxSizeMode.CenterImage;
                else this.pictureBoxDisplay.SizeMode = PictureBoxSizeMode.Zoom;
        }

        private void buttonIncrease_Click(object sender, EventArgs e)
        {
            trackBarZoom.Visible = !trackBarZoom.Visible;
        }

        private void buttonOpen_Click(object sender, EventArgs e)
        {
            if ((openFileDialog.ShowDialog() == DialogResult.OK) &&
                (openFileDialog.FileName != ""))
            {
                DisplayImage(openFileDialog.FileName);
                FillArray(openFileDialog.FileName);
            }
        }

        private void labelTitle_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                ReleaseCapture();
                SendMessage(Handle, WM_NCLBUTTONDOWN, HTCAPTION, 0);
            }
        }

        private void pictureBoxIcon_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                ReleaseCapture();
                SendMessage(Handle, WM_NCLBUTTONDOWN, HTCAPTION, 0);
            }
        }

        private void panelUpper_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                ReleaseCapture();
                SendMessage(Handle, WM_NCLBUTTONDOWN, HTCAPTION, 0);
            }
        }

        private void buttonDelete_Click(object sender, EventArgs e)
        {
            if ((LastPath!=null))
            {
                DeleteForm df = new DeleteForm();
                if(df.ShowDialog() == DialogResult.Yes)
                {
                    if (pictureBoxDisplay.Image != null)
                    {
                        pictureBoxDisplay.Image.Dispose();
                        pictureBoxDisplay.Image = null;
                    }
                    this.labelError.Visible = false;
                    File.Delete(LastPath);
                    if (LastPath == Files[Index])
                    {
                        Files.RemoveAt(Index);
                        if (Index >= Files.Count) Index = 0;
                        if (Files.Count != 0) DisplayImage(Files[Index]);
                    }
                    else
                    {
                        Index++;
                        if (Index >= Files.Count) Index = 0;
                        if (Files.Count != 0) DisplayImage(Files[Index]);
                    }
                }
            }
        }

        private void buttonNext_Click(object sender, EventArgs e)
        {
            if (Files.Count != 0)
            {
                if (Index >= Files.Count - 1)
                    Index = 0;
                else Index++;
                DisplayImage(Files[Index]);
            }
        }

        private void buttonPrevious_Click(object sender, EventArgs e)
        {
            if (Files.Count != 0)
            {
                if (Index <= 0)
                    Index = Files.Count - 1;
                else if(LastPath==Files[Index]) Index--;
                DisplayImage(Files[Index]);
            }
        }

        private void buttonTurnRight_Click(object sender, EventArgs e)
        {
            if (pictureBoxDisplay.Image != null)
                pictureBoxDisplay.Image.RotateFlip(RotateFlipType.Rotate90FlipNone);
            pictureBoxDisplay.Refresh();
        }

        private void buttonTurnLeft_Click(object sender, EventArgs e)
        {
            if (pictureBoxDisplay.Image != null)
                pictureBoxDisplay.Image.RotateFlip(RotateFlipType.Rotate270FlipNone);
            pictureBoxDisplay.Refresh();
        }

        #region SavelyDragDrop

        private void MainForm_DragDrop(object sender, DragEventArgs e)
        {
            string file = GetFilename(e);
            DisplayImage(file);
            FillArray(file);
        }

        private void MainForm_DragEnter(object sender, DragEventArgs e)
        {
            e.Effect = DragDropEffects.Copy;
        }

        protected string GetFilename(DragEventArgs e)
        {
            if ((e.AllowedEffect & DragDropEffects.Copy) == DragDropEffects.Copy)
            {
                Array data = ((IDataObject)e.Data).GetData("FileDrop") as Array;
                if (data != null)
                {
                    if ((data.Length == 1) && (data.GetValue(0) is String))
                    {
                        return ((string[])data)[0];
                    }
                }
            }
            return "";
        }
        #endregion EndSavelyDragDrop
    }
}